//
//  MasterViewController.m
//  PedometerTest
//
//  Created by Leming Deng on 2014-07-23.
//  Copyright (c) 2014 tdr. All rights reserved.
//

#import "MasterViewController.h"
#import <CoreMotion/CoreMotion.h>
#import "NSDate+format.h"

#pragma mark - Definitions
enum SectionList {
    SectionAvailablility = 0,
    SectionPeriod,
    SectionData,
    SectionCount
};

enum SectionAvailablilityItems {
    AvailablityStepCounting = 0,
    AvailablityDistance,
    AvailablityFloorCounting,
    AvailablityCount
};

enum SectionPeriodItems {
    PeriodStart = 0,
    PeriodEnd,
    PeriodCount
};

#pragma mark -
@interface MasterViewController () {
    CMPedometerHandler handler;
}

@property NSMutableArray *objects;
@property NSDate *startDate;
@property NSDate *endDate;

- (CMPedometer *)predometer;
@end

@implementation MasterViewController
            
- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    __weak typeof(self) weakself = self;
    handler = ^(CMPedometerData *pedometerData, NSError *error) {
        if (error) {
            NSLog(@"Error getting pedometerData: %@", error);
        } else {
            [weakself insertNewObject:pedometerData];
        }
    };
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)insertNewObject:(id)object {
    if (object) {
        if (!self.objects) {
            self.objects = [[NSMutableArray alloc] init];
        }
        [self.objects insertObject:object atIndex:0];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:SectionData];
        [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (CMPedometer *)predometer {
    static CMPedometer *cmp = nil;
    if (cmp == nil) {
        cmp = [[CMPedometer alloc] init];
    }
    return cmp;
}
#pragma mark - Segues

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        switch (indexPath.row) {
            case PeriodStart:
                [[segue destinationViewController] setTitle:@"From"];
                [[segue destinationViewController] setDateItem:self.startDate];
                break;
            case PeriodEnd:
                [[segue destinationViewController] setTitle:@"To"];
                [[segue destinationViewController] setDateItem:self.endDate];
                break;
            default:
                break;
        }
        DateViewController *c = [segue destinationViewController];
        [c setDelegate:self];
    }
}

#pragma mark - Table View Datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return SectionCount;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger result = 0;
    switch (section) {
        case SectionAvailablility:
            result = AvailablityCount;
            break;
        case SectionPeriod:
            result = PeriodCount;
            break;
        case SectionData:
            result = [self.objects count];
            break;
        default:
            break;
    }
    return result;
}

- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
    NSString *title = @"";
    switch (section) {
        case SectionAvailablility:
            title = @"Availablility";
            break;
        case SectionPeriod:
            title = @"Period";
            break;
        case SectionData:
            title = @"PedometerData";
            break;
            
        default:
            break;
    }
    return title;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    switch (indexPath.section) {
        case SectionAvailablility:
            [cell.detailTextLabel setText:nil];
            switch (indexPath.row) {
                case AvailablityDistance:
                    [cell.textLabel setText:@"Distance"];
                    if ([CMPedometer isDistanceAvailable]) {
                        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
                    }
                    break;
                case AvailablityFloorCounting:
                    [cell.textLabel setText:@"FloorCounting"];
                    if ([CMPedometer isFloorCountingAvailable]) {
                        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
                    }
                    break;
                case AvailablityStepCounting:
                    [cell.textLabel setText:@"StepCounting"];
                    if ([CMPedometer isStepCountingAvailable]) {
                        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
                    }
                    break;
                default:
                    break;
            }
            
            break;
        case SectionPeriod:
            [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
            [cell setUserInteractionEnabled:YES];
            switch (indexPath.row) {
                case PeriodStart:
                    [cell.textLabel setText:@"From"];
                    [cell.detailTextLabel setText:[self.startDate description]];
                    break;
                case PeriodEnd:
                    [cell.textLabel setText:@"To"];
                    [cell.detailTextLabel setText:[self.endDate description]];
                    break;
                default:
                    break;
            }
            break;
        case SectionData:
            [cell.detailTextLabel setText:nil];
            [cell.textLabel setFont:[UIFont systemFontOfSize:8]];
            [cell.textLabel setLineBreakMode:NSLineBreakByWordWrapping];
            [cell.textLabel setNumberOfLines:0];
            [cell.textLabel setText:[[self.objects objectAtIndex:indexPath.row] description]];
            break;
        default:
            break;
    }
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return NO;
}

#pragma mark - UI Actions

- (IBAction)monitorTapped:(id)sender {
    @synchronized (self) {
        UIBarButtonItem *item = sender;
        if (item.tag == 0) {
            [item setTag:1];
            [item setTitle:@"Stop"];
            NSDate *start = [NSDate date];
            if (self.startDate != nil) {
                start = self.startDate;
            }
            [[self predometer] startPedometerUpdatesFromDate:start withHandler:handler];
        } else {
            [item setTag:0];
            [item setTitle:@"Monitor"];
            [[self predometer] stopPedometerUpdates];
        }
    }

}


- (IBAction)queryTapped:(id)sender {
    NSString *errMsg = nil;
    if (self.startDate != nil && self.endDate != nil) {
        if ([self.startDate compare:self.endDate] == NSOrderedAscending) {
            [[self predometer] queryPedometerDataFromDate:self.startDate toDate:self.endDate withHandler:handler];
        } else {
            errMsg = @"Periods invalid";
        }
    } else {
        errMsg = @"Periods need to be set";
    }
    
    if (errMsg != nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:errMsg delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark - Date Selection Delegate
- (void)dataSelectionView:(DateViewController *)controller willFinishWithDate:(NSDate *)date {
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    switch (indexPath.row) {
        case PeriodStart:
            self.startDate = date;
            break;
        case PeriodEnd:
            self.endDate = date;
            break;
    }
    [self.tableView reloadData];
}

@end
